using Dapper;
using InventoryIssue.API.Write.Application.Command.Allocate;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;

namespace InventoryIssue.API.Write.Application.Handler.Allocate
{
    /// <summary>
    /// 创建入库记录处理器
    /// </summary>
    public class CreateInboundRecordHandler : IRequestHandler<CreateInboundRecordCommand, APIResult<int>>
    {
        private readonly DatabaseContext db;

        public CreateInboundRecordHandler(DatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(CreateInboundRecordCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            try
            {
                // 验证调拨单是否存在
                int allocateExists;
                try
                {
                    allocateExists = await db.DapperConnection.QueryFirstOrDefaultAsync<int>(
                        "SELECT COUNT(1) FROM allocatemodel WHERE AllocateId = @AllocateId AND IsDel = 0",
                        new { request.AllocateId });
                }
                catch (Exception ex) when (ex.Message.Contains("doesn't exist") || ex.Message.Contains("不存在"))
                {
                    result.Code = APIEnum.Fail;
                    result.Message = "数据库表不存在，请先创建相关表";
                    return result;
                }

                if (allocateExists == 0)
                {
                    result.Code = APIEnum.Fail;
                    result.Message = "调拨单不存在";
                    return result;
                }

                // 生成入库记录ID
                int inboundRecordId;
                try
                {
                    inboundRecordId = await db.DapperConnection.QueryFirstOrDefaultAsync<int>(
                        "SELECT COALESCE(MAX(InboundRecordId), 0) + 1 FROM inboundrecordmodel");
                }
                catch (Exception ex) when (ex.Message.Contains("doesn't exist") || ex.Message.Contains("不存在"))
                {
                    result.Code = APIEnum.Fail;
                    result.Message = "入库记录表不存在，请先创建相关表";
                    return result;
                }

                // 插入入库记录
                var sql = @"
                    INSERT INTO inboundrecordmodel (
                        InboundRecordId, AllocateId, InboundDate, Quantity, 
                        InboundWarehouse, InboundLocation, InboundOperator, Note, 
                        CreateTime, UpdateTime, IsDel
                    ) VALUES (
                        @InboundRecordId, @AllocateId, @InboundDate, @Quantity,
                        @InboundWarehouse, @InboundLocation, @InboundOperator, @Note,
                        @CreateTime, @UpdateTime, 0
                    )";

                var parameters = new
                {
                    InboundRecordId = inboundRecordId,
                    request.AllocateId,
                    request.InboundDate,
                    request.Quantity,
                    request.InboundWarehouse,
                    request.InboundLocation,
                    request.InboundOperator,
                    request.Note,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };

                await db.DapperConnection.ExecuteAsync(sql, parameters);

                // 更新调拨单状态为已入库
                await db.DapperConnection.ExecuteAsync(
                    "UPDATE allocatemodel SET State = 5, UpdateTime = @UpdateTime WHERE AllocateId = @AllocateId",
                    new { AllocateId = request.AllocateId, UpdateTime = DateTime.Now });

                result.Code = APIEnum.Ok;
                result.Message = "入库记录创建成功";
                result.Data = inboundRecordId;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Message = $"创建入库记录失败: {ex.Message}";
            }

            return result;
        }
    }
} 